package icu.guodapeng.website.domain.user.holder

import cn.hutool.core.convert.Convert
import cn.hutool.json.JSONObject
import icu.guodapeng.website.domain.user.dto.UserDto
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes

/**
 * 获取登录用户信息
 */
@Component
class LoginUserHolder {
    fun getCurrentUser(): UserDto {
        // 从 Header 中获取用户信息
        val servletRequestAttributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
        val request = servletRequestAttributes.request
        val userStr = request.getHeader("user")
        val userJsonObject = JSONObject(userStr)
        val userDto = UserDto()
        userDto.id = Convert.toLong(userJsonObject["id"])
        userDto.username = userJsonObject.getStr("user_name")
        userDto.roles = Convert.toList(String::class.java, userJsonObject["authorities"])
        return userDto
    }
}
